// 楼盘一级路由
import React, { useEffect, useState } from 'react';
// 引入路由组件
import { NavLink, Outlet, useNavigate } from 'react-router-dom';
// 引入封装的axios
import request from '../http/request.js';
// 引入组件库
import { PageContainer, ProCard } from '@ant-design/pro-components';
import { UserOutlined, BankFilled, PoweroffOutlined, ExclamationCircleFilled } from '@ant-design/icons';
import { Layout, Menu, theme, message, Tabs, Tooltip, Modal } from 'antd';
// 引入路由表  
//            楼盘                     客服
import { propertyManagementChildren, customerserviceChildren, usedrentedChildren } from '../router/index';
// 引入样式
import homeCss from './Home.module.css';
// 引入高阶组件
import Hoc_login from '../http/Hoc_Login';
// 引入 状态管理库和方法
import { useDispatch, useSelector } from 'react-redux';
import { addPageContainer, delPageContainer } from '../store/reducer/HomeSlice';
const { confirm } = Modal;

// antd 组件库
const { Header, Content, Sider } = Layout;

function Home() {
    const navigate = useNavigate()
    // 实例化状态管理库方法
    const dispatch = useDispatch()
    // const { value } = useSelector(state => state.HomeSlice)
    // 仓库标签表数据
    const { pageContainerTabList } = useSelector(state => state.HomeSlice);
    // 标签表
    const [pageContainerData, setPageContainerData] = useState([])
    // 获取token
    let token = localStorage.getItem('token')
    const [userObj, setUserObj] = useState({})
    // 用于渲染的路由表
    const [chilRouterList, setChilRouterList] = useState(propertyManagementChildren)
    // 页面标签高亮项
    const [tabPageActive, setTabPageActive] = useState('基础面板')

    // 获取用户信息和解密
    useEffect(() => {
        if (token) {
            // console.log(token)
            request.get('/api/verify', { params: { token } }).then(res => {
                console.log('res', res)
                if (res.code != 200) {
                    navigate('/login')
                    message.error(res.msg)
                    return;
                }
                setUserObj(res.userObj)
            })
        }

    }, [])

    // 处理标签渲染数据
    useEffect(() => {
        const newList = [];
        pageContainerTabList.forEach((item, index) => {
            newList.push({
                tab: <NavLink to={item.path}>{item.tab}</NavLink>,
                key: item.key,
                closable: index == 0 ? false : true
            })
        })
        setTabPageActive(pageContainerTabList[pageContainerTabList.length - 1].key)
        navigate(pageContainerTabList[pageContainerTabList.length - 1].path)
        setPageContainerData(newList)
    }, [pageContainerTabList])

    // 处理侧边导航栏要的渲染数据
    const renderSideList = (arr) => {
        return arr.map((item, index) => {
            // 判断路由是否存在权限标识
            if (item.role) {
                // 判断路由权限
                if (item.role == userObj.role) {
                    return {
                        key: item.meta,
                        icon: item.icon,
                        label: item.children ? item.meta : <Tooltip placement="right" title={item.meta}>
                            <NavLink to={item.path} onClick={async () => {
                                if (!item.children) {
                                    console.log('没有子级')
                                    item.element = {}
                                    await dispatch(addPageContainer(item))
                                }
                            }}><div>
                                    {item.meta}
                                </div>
                            </NavLink>
                        </Tooltip>,
                        children: item.children && renderSideList(item.children)
                    }
                }
            } else {

                return {
                    key: item.meta,
                    icon: item.icon,
                    label: item.children ? item.meta : <Tooltip placement="right" title={item.meta}>
                        <NavLink to={item.path} onClick={async () => {
                            if (!item.children) {
                                console.log('没有子级')
                                item.element = {}
                                await dispatch(addPageContainer(item))
                            }
                        }}><div>
                                {item.meta}
                            </div>
                        </NavLink>
                    </Tooltip>,
                    children: item.children && renderSideList(item.children)
                }
            }
        });
    }

    // 侧边导航选项内容
    const sideList = renderSideList(chilRouterList);

    const {
        token: { colorBgContainer },
    } = theme.useToken();

    // headertab 改变
    const onChange = (key) => {
        console.log(key);
        if (key == '1') {
            setChilRouterList(propertyManagementChildren)
        } else if (key == '2') {
            setChilRouterList(customerserviceChildren)
        } else if (key == '3') {
            setChilRouterList(usedrentedChildren)
        }
    };

    // headertab 数据
    const items = [
        {
            key: '1',
            label: <><BankFilled />楼盘</>,
        },
        {
            key: '2',
            label: <>< UserOutlined />客服</>,
        },
        {
            key: '3',
            label: <>< UserOutlined />二手/出租</>,
        }
    ];

    // tabList 删除功能
    function deleteTabList(type) {
        dispatch(delPageContainer(type))
    }

    //退出登录的提示确认框
    const showDeleteConfirm = async () => {
        confirm({
            title: '你确定要退出登录吗?',
            icon: <ExclamationCircleFilled />,
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            async onOk() {
                console.log('OK');
                localStorage.clear('token')
                await message.success({
                    type: 'success',
                    content: '退出登录成功',
                    duration: 1,
                });
                // 刷新页面
                window.location.reload()
            },
            onCancel() {
                console.log('Cancel');
            },
        });

    }

    return <div className='homeElement'>
        <Layout>
            {/* 头部布局 */}
            <Header
                style={{
                    padding: 0,
                    display: 'flex',
                    alignItems: 'center',
                    background: '#eee',
                    position: 'relative',
                }}
            >
                <div className={homeCss.home_h3}>后台管理中心</div>
                <div className={homeCss.headerTab}>
                    <Tabs defaultActiveKey="1" items={items} onChange={onChange} />
                </div>
                <div className={homeCss.userObj}>
                    <span>欢迎您！{userObj?.username}</span>
                    <span className={homeCss.outUser} onClick={showDeleteConfirm}><PoweroffOutlined />注销</span>
                </div>
            </Header>
            <Layout>
                <Sider
                    width={200}
                    style={{
                        background: colorBgContainer,
                    }}
                >
                    <Menu
                        mode="inline"
                        // // 默认高亮的子级的侧边导航选项
                        // defaultSelectedKeys={['楼盘列表']}
                        // // 默认开启得到有子级的侧边导航
                        // defaultOpenKeys={['楼盘管理']}
                        style={{
                            height: '100%',
                            borderRight: 0,
                        }}
                        items={sideList}
                    />
                </Sider>
                <Layout>
                    <Content
                        style={{
                            margin: 0,
                            minHeight: 280,
                            padding: 0,
                            background: colorBgContainer,
                        }}
                    >
                        <div
                            style={{
                                background: '#F5F7FA',
                            }}
                        >
                            {/* 页面标签栏 */}
                            <PageContainer
                                fixedHeader
                                tabActiveKey={tabPageActive}
                                tabList={pageContainerData}
                                onTabChange={(key) => {
                                    console.log(key, '切换面板')
                                    setTabPageActive(key)
                                }}
                                tabProps={{
                                    type: 'editable-card',
                                    hideAdd: true,
                                    onEdit: (e, action) => deleteTabList(e),
                                }}
                            >
                                <ProCard direction="column" ghost  >
                                    {/* 高度继承 */}
                                    <ProCard style={{ height: "100%" }} >
                                        <Outlet></Outlet>
                                    </ProCard>
                                </ProCard>
                            </PageContainer>
                        </div>
                    </Content>
                </Layout>
            </Layout>
        </Layout>
    </div>
}

export default Hoc_login(Home)